// utils/speechManager.js

class SpeechManager {
  constructor() {
    this.platform = uni.getSystemInfoSync().platform;
    this.recorderManager = null;
    this.recognition = null;
    this.isRecording = false;
    this.resolve = null;
    this.reject = null;
     this.initH5();
  }

  // 初始化
  init() {
    switch (this.platform) {
      case 'mp-weixin':
        this.initWechat();
        break;
      case 'app':
        this.initApp();
        break;
      case 'h5':
        this.initH5();
        break;
      default:
        console.warn('不支持的平台:', this.platform);
    }
  }

  // 微信小程序初始化
  initWechat() {
    // #ifdef MP-WEIXIN
    this.recorderManager = wx.getRecorderManager();
    this.setWechatEvents();
    // #endif
  }

  // APP平台初始化
  initApp() {
    // #ifdef APP-PLUS
    // 尝试使用原生录音API
    try {
      // 这里可以使用uni的API或者第三方插件
      console.log('APP平台语音识别初始化');
    } catch (error) {
      console.warn('APP平台语音识别初始化失败:', error);
    }
    // #endif
  }

  // H5平台初始化
  initH5() {
    // #ifdef H5
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
      this.recognition = new SpeechRecognition();
      this.recognition.continuous = false;
      this.recognition.interimResults = false;
      this.recognition.lang = 'zh-CN';
      this.setH5Events();
    } else {
      console.warn('浏览器不支持语音识别API');
    }
    // #endif
  }

  // 设置微信小程序事件监听
  setWechatEvents() {
    // #ifdef MP-WEIXIN
    this.recorderManager.onStart(() => {
      console.log('录音开始');
      this.isRecording = true;
    });

    this.recorderManager.onStop((res) => {
      console.log('录音结束', res);
      this.isRecording = false;
      this.handleWechatRecordResult(res);
    });

    this.recorderManager.onError((err) => {
      console.error('录音错误', err);
      this.isRecording = false;
      if (this.reject) {
        this.reject(new Error('录音失败: ' + err.errMsg));
      }
    });
    // #endif
  }

  // 设置H5事件监听
  setH5Events() {
    // #ifdef H5
    this.recognition.onresult = (event) => {
      const transcript = event.results[0][0].transcript;
      console.log('H5语音识别结果:', transcript);
      if (this.resolve) {
        this.resolve(transcript);
      }
    };

    this.recognition.onerror = (event) => {
      console.error('H5语音识别错误:', event.error);
      if (this.reject) {
        this.reject(new Error(event.error));
      }
    };

    this.recognition.onend = () => {
      this.isRecording = false;
    };
    // #endif
  }

  // 开始语音识别
  startRecognition(options = {}) {
    return new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;

      const config = {
        lang: 'zh-CN',
        duration: 60000,
        ...options
      };

      switch (this.platform) {
        case 'mp-weixin':
          this.startWechatRecognition(config);
          break;
        case 'app':
          this.startAppRecognition(config);
          break;
        case 'h5':
          this.startH5Recognition(config);
          break;
        default:
          reject(new Error('不支持的平台'));
      }
    });
  }

  // 微信小程序开始录音
  startWechatRecognition(config) {
    // #ifdef MP-WEIXIN
    this.recorderManager.start({
      duration: config.duration,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    });
    // #endif
  }

  // APP平台开始录音
  startAppRecognition(config) {
    // #ifdef APP-PLUS
    // 使用uni的录音API
    uni.startRecord({
      success: (res) => {
        console.log('APP录音开始');
        this.isRecording = true;
      },
      fail: (err) => {
        console.error('APP录音失败', err);
        if (this.reject) {
          this.reject(new Error('APP录音失败: ' + JSON.stringify(err)));
        }
      }
    });

    // 设置自动停止计时器
    setTimeout(() => {
      if (this.isRecording) {
        this.stopRecognition();
      }
    }, config.duration);
    // #endif
  }

  // H5平台开始录音
  startH5Recognition(config) {
    // #ifdef H5
    if (this.recognition) {
      this.recognition.start();
      this.isRecording = true;
    } else {
      if (this.reject) {
        this.reject(new Error('浏览器不支持语音识别'));
      }
    }
    // #endif
  }

  // 停止语音识别
  stopRecognition() {
    switch (this.platform) {
      case 'mp-weixin':
        // #ifdef MP-WEIXIN
        if (this.recorderManager) {
          this.recorderManager.stop();
        }
        // #endif
        break;
      case 'app':
        // #ifdef APP-PLUS
        uni.stopRecord();
        this.isRecording = false;
        // #endif
        break;
      case 'h5':
        // #ifdef H5
        if (this.recognition) {
          this.recognition.stop();
        }
        // #endif
        break;
    }
  }

  // 取消语音识别
  cancelRecognition() {
    this.isRecording = false;
    this.resolve = null;
    this.reject = null;

    switch (this.platform) {
      case 'mp-weixin':
        // #ifdef MP-WEIXIN
        if (this.recorderManager) {
          this.recorderManager.stop();
        }
        // #endif
        break;
      case 'h5':
        // #ifdef H5
        if (this.recognition) {
          this.recognition.abort();
        }
        // #endif
        break;
    }
  }

  // 处理微信小程序录音结果
  async handleWechatRecordResult(res) {
    try {
      // 微信小程序需要调用语音识别接口
      const text = await this.wechatSpeechRecognition(res.tempFilePath);
      if (this.resolve) {
        this.resolve(text);
      }
    } catch (error) {
      console.error('微信语音识别失败:', error);
      if (this.reject) {
        this.reject(error);
      }
    }
  }

  // 微信小程序语音识别
  wechatSpeechRecognition(tempFilePath) {
    return new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN
      // 微信小程序的语音识别
      wx.startRecord({
        success: (res) => {
          resolve(res.result);
        },
        fail: (err) => {
          reject(new Error('微信语音识别失败: ' + JSON.stringify(err)));
        }
      });
      // #else
      reject(new Error('非微信小程序平台'));
      // #endif
    });
  }

  // 检查是否支持语音识别
  isSupported() {
    switch (this.platform) {
      case 'mp-weixin':
        return true;
      case 'app':
        return true;
      case 'h5':
        return !!this.recognition;
      default:
        return false;
    }
  }

  // 获取平台信息
  getPlatform() {
    return this.platform;
  }

  // 检查是否正在录音
  getIsRecording() {
    return this.isRecording;
  }

  // 设置语言
  setLanguage(lang) {
    switch (this.platform) {
      case 'h5':
        // #ifdef H5
        if (this.recognition) {
          this.recognition.lang = lang;
        }
        // #endif
        break;
      // 其他平台的语言设置...
    }
  }
}

// 创建单例实例
const speechManager = new SpeechManager();

export default speechManager;